package web

import (
	"context"
	"fmt"
	"github.com/liangdas/mqant/conf"
	"github.com/liangdas/mqant/log"
	"github.com/liangdas/mqant/module"
	"github.com/liangdas/mqant/module/base"
	"github.com/liangdas/mqant/rpc"
	"io"
	"net/http"
)

var Module = func() module.Module {
	this := new(Web)
	return this
}

type Web struct {
	basemodule.BaseModule
}

func (w *Web) GetType() string {
	//很关键,需要与配置文件中的Module配置对应
	return "Web"
}
func (w *Web) Version() string {
	//可以在监控时了解代码版本
	return "1.0.0"
}
func (w *Web) OnAppConfigurationLoaded(app module.App)  {
	//当App初始化时调用，这个接口不管这个模块是否在这个进程运行都会调用
	w.BaseModule.OnAppConfigurationLoaded(app)
	log.Info("%v OnAppConfigurationLoaded...", w.GetType())
}

func (w *Web) OnInit(app module.App, settings *conf.ModuleSettings) {
	w.BaseModule.OnInit(w, app, settings)
	log.Info("%v OnInit...", w.GetType())
}

func (w *Web)startHttpServer() *http.Server {
	host := w.GetModuleSettings().Host
	settings := w.GetModuleSettings().Settings
	fmt.Printf("startHttpServer   %#v\n",host)
	fmt.Printf("startHttpServer   %#v\n",settings)

	srv := &http.Server{Addr: ":8080"}
	http.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
		_ = r.ParseForm()
		rStr,err := mqrpc.String(
			w.Call(
				context.Background(),
				"HelloWorld",
				"/say/hi",
				mqrpc.Param(r.Form.Get("name")),
			),
		)
		log.Info("RpcCall %v , err %v",rStr,err)
		_, _ = io.WriteString(rw, rStr)
	})
	go func() {
		if err := srv.ListenAndServe(); err != nil {
			// cannot panic, because this probably is an intentional close
			log.Info("Httpserver: ListenAndServe() error: %s", err)
		}
	}()
	// returning reference so caller can call Shutdown()
	return srv
}

func (w *Web) Run(closeSig chan bool) {
	log.Info("web: starting HTTP server :8080")
	srv := w.startHttpServer()
	<-closeSig
	log.Info("web: stopping HTTP server")
	// now close the server gracefully ("shutdown")
	// timeout could be given instead of nil as a https://golang.org/pkg/context/

	ctx,_ := context.WithCancel(context.Background())
	if err := srv.Shutdown(ctx); err != nil {
		panic(err) // failure/timeout shutting down the server gracefully
	}
	log.Info("web: done. exiting")
}

func (w *Web) OnDestroy() {
	//一定别忘了继承
	w.BaseModule.OnDestroy()
}